<!--
 * @Descripttion:
 * @version: 1.0.0
 * @Author: htang
 * @Date: 2024-01-15 15:38:30
 * @LastEditors: htang
 * @LastEditTime: 2024-04-11 10:37:32
-->
<template>
  <div class="jeecg-basic-table station-list-view device-container">
    <div class="tip">
      <span>水厂视频监控</span>
      <span class="tip-img"></span>
    </div>
    <div class="jeecg-table-view flex">
      <div class="tree-meun">
        <a-tree v-model="selectedKeys" :tree-data="treeData" showLine :load-data="onLoadData" @select="onSelect" :multiple="false">
          <template #title="vo">
            <div class="flex items-center">
              <span>{{ vo.name }}</span>
              <template v-if="vo['basicData']">
                <span class="status" :class="vo['basicData']['status'] ? 'on-line' : 'off-line'"></span>
              </template>
            </div>
          </template>
        </a-tree>
      </div>

      <div class="play-container">
        <div class="play-head flex items-center justify-between">
          <div class="flex items-center">
            <span>分屏</span>
            <i class="ico icon-1" title="单屏" :class="[spilt == 1 ? 'active' : '']" @click="spilt = 1"></i>
            <i class="ico icon-2" title="四屏" :class="[spilt == 4 ? 'active' : '']" @click="spilt = 4"></i>
            <template v-if="spinning">
              <a-alert message="视频加载中..." type="warning" />
            </template>
          </div>
        </div>
        <div class="player-main flex flex-wrap h-full">
          <template v-for="i in spilt" :key="i">
            <div class="player" :style="liveStyle" @click="getPlayIndex(i)">
              <div class="h-full" :style="[playerIndex == i ? 'border: 2px solid red' : '']">
                <!-- <template v-if="!videoUrl[i]">
                  <div class="number flex items-center justify-center">
                    <a-spin :spinning="spinning">
                      <span>{{ i }}</span>
                    </a-spin>
                  </div>
                </template>
                <template v-else> -->
                <!-- <a-spin tip="Loading..." :spinning="spinning"> -->
                <!-- <video :src="videoUrl[i]" controls autoplay class="video"></video> -->
                <div ref="player" class="player-container" :id="'player-' + i"></div>
                <!-- </a-spin> -->
                <!-- </template> -->
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import {
  ExpandOutlined,
  AppstoreOutlined,
  TableOutlined,
  CaretRightOutlined,
  PauseOutlined,
  ShrinkOutlined,
  ArrowsAltOutlined,
  RedoOutlined,
  cameraIdentificationUpdateApi,
} from '@ant-design/icons-vue';
import Player from './components/jessibuca.vue';
export default defineComponent({
  components: {
    ExpandOutlined,
    AppstoreOutlined,
    TableOutlined,
    CaretRightOutlined,
    PauseOutlined,
    ShrinkOutlined,
    ArrowsAltOutlined,
    RedoOutlined,
    Player,
  },
});
</script>

<script lang="ts" setup>
import '@/assets/js/jessibuca/jessibuca.js';
import { ref, watch, computed, getCurrentInstance, nextTick, onMounted, onUnmounted } from 'vue';
import { deviceQueryApi, deviceQueryTeeApi, deviceCameraPlayApi } from '@/api/camera/play';
import { wvpDevicesApi, wvpDeviceTreeApi, wvpPlayStartApi } from '/@/api/wvp/index';
import { useUserStore } from '/@/store/modules/user';
import { stationListApi } from '@/api/station/index';
import { useMessage } from '/@/hooks/web/useMessage';
import { CAMERA_CONFIG as cameraConfig } from '/@/utils/index.ts';
import type { TreeProps, Modal, message } from 'ant-design-vue';

const { createMessage } = useMessage();

const userStore = useUserStore();

let { proxy } = getCurrentInstance();

let spinning = ref(false);

let treeData = ref<TreeProps['treeData']>([]);

let selectedKeys = ref([]);

let videoUrl = ref([]);

// 站点列表
let stationList = ref();

let playList = new Array(4).fill({});

// 站点名称
let stationNames = ref([]);

let playerIndex = ref(1);

let spilt = ref(1);

let ipagination = ref({
  current: 1,
  pageSize: 100000,
  pageSizeOptions: ['10', '20', '30'],
  showTotal: (total, range) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条';
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0,
});

let borderStyle = computed(() => {
  playerIndex.value;
});

let liveStyle = computed(() => {
  let style = { width: '100%', height: '100%' };
  switch (spilt.value) {
    case 4:
      style = { width: '50%', height: '50%' };
      break;
    case 9:
      style = { width: '33.3%', height: '33.3%' };
      break;
    default:
      break;
  }
  nextTick(() => {
    for (let i = 0; i < spilt.value; i++) {
      const player = proxy.$refs.player;
      // player && player[i] && player[i].updatePlayerDomSize();
    }
  });
  return style;
});

watch(
  () => spilt.value,
  (total) => {
    let array = [];
    for (let i = 1; i <= total; i++) {
      array[i - 1] = videoUrl.value[i - 1];
    }
    videoUrl.value = array;
  }
);

function created(id) {
  let node = document.getElementById(`player-${id}`);
  if (node) {
    let kBps = 0;
    let jessibuca = new window.Jessibuca({
      container: node,
      autoWasm: true,
      background: '',
      controlAutoHide: false,
      debug: false,
      decoder: new URL(`@/assets/js/jessibuca/decoder.js`, import.meta.url).href,
      videoBuffer: 0.2, // 最大缓冲时长，单位秒
      isResize: false,
      forceNoOffscreen: false,
      heartTimeout: 5,
      heartTimeoutReplay: true,
      heartTimeoutReplayTimes: 3,
      hiddenAutoPause: false,
      hotKey: true,
      isFlv: false,
      isFullResize: false,
      keepScreenOn: true,
      loadingText: '请稍等, 视频加载中......',
      loadingTimeout: 10,
      loadingTimeoutReplay: true,
      loadingTimeoutReplayTimes: 3,
      openWebglAlignment: false,
      operateBtns: {
        fullscreen: true,
        screenshot: true,
        play: true,
        audio: true,
        record: false,
      },
      recordType: 'mp4',
      rotate: 0,
      showBandwidth: false,
      supportDblclickFullscreen: false,
      timeout: 10,
      useMSE: true,
      isNotMute: false,
      record: 'record',
      useWCS: location.hostname === 'localhost' || location.protocol === 'https:',
      useWebFullScreen: true,
      wasmDecodeErrorReplay: true,
      wcsUseVideoRender: true,
    });
    jessibuca.on('kBps', (data) => {
      // kBps.value = Math.round(data);
    });
    if (jessibuca.hasLoaded()) {
      jessibuca.play(videoUrl.value[playerIndex.value]);
    } else {
      jessibuca.on('load', () => {
        jessibuca.play(videoUrl.value[playerIndex.value]);
      });
    }
    playList[id - 1] = jessibuca;
  }
}

/**
 * 初始化所有设备数据
 */
function onInitDeviceQuery() {
  let { current, pageSize } = ipagination.value;
  let data = {
    page: current,
    count: pageSize,
  };
  deviceQueryApi(data).then(({ list }) => {
    const userInfo = userStore.getUserInfo;
    let names = stationNames.value;
    if (userInfo.username !== 'admin') {
      treeData.value = list.filter((_) => {
        if (names.includes(_['name'])) {
          _['title'] = _['name'] == 'beijiao' ? '北滘水厂' : _['name'];
          _['key'] = _['deviceId'];
          return _;
        }
      });
    } else {
      if (list.length == 0) {
      } else {
        treeData.value = list.map((_) => {
          _['title'] = _['name'] == 'beijiao' ? '北滘水厂' : _['name'];
          _['key'] = _['deviceId'];
          return _;
        });
      }
    }
  });
}

function onLoadData(treeNode) {
  return new Promise((resolve) => {
    let deviceId = treeNode.deviceId;
    if (!treeNode.dataRef.ip) {
      resolve('');
      return;
    }
    wvpDeviceTreeApi(deviceId, { viewType: 1 }).then(({ list }) => {
      interface childType {
        key: string;
        title: string;
      }
      let children: childType[] = [];
      list.map((_) => {
        delete _['parent'];
        children.push({
          key: `${treeNode.eventKey}-${_['id']}`,
          title: _['name'],
          ..._,
          isLeaf: true,
        });
      });
      treeNode.dataRef.children = children;
      treeData.value = [...treeData.value];
      resolve(list);
    });
  });
}

/**
 * 选择摄像头播放视频流
 */
function onSelect(data, event) {
  selectedKeys.value = data.length ? [data[data.length - 1]] : [];
  if (event.selectedNodes[0]) {
    let { deviceId, basicData } = event.selectedNodes[0];
    let stationName = event?.node?.parent?.node?.name;
    if (basicData) {
      spinning.value = true;
      let query = {
        deviceId,
        channelId: basicData['channelId'],
      };
      wvpPlayStartApi(query, {
        stationName,
      })
        .then((res) => {
          spinning.value = false;
          let path = '';
          // path = res.fmp4;
          path = res.ws_flv;
          videoUrl.value[playerIndex.value] = path;
          if (Object.keys(playList[playerIndex.value - 1]).length !== 0) {
            playList[playerIndex.value - 1].destroy();
          }
          created(playerIndex.value);
        })
        .catch((error) => {
          // message.error('加载失败，请重新点击!');
          spinning.value = false;
        });
    }
  }
}

/**
 * 销毁后回调事件
 */
function onDestroy() {
  videoUrl.value.splice(playerIndex.value, 1, undefined);
}

/**
 * 获取视频分屏索引
 */
function getPlayIndex(i) {
  playerIndex.value = i;
}

/**
 * 初始化站点
 */
function initStation() {
  let stationCodes = userStore.getUserInfo['stationCodes'];
  let data = {};
  if (stationCodes) {
    data['stationCodes'] = stationCodes;
  }
  wvpDevicesApi(data).then((res) => {
    treeData.value = res.list.map((k) => {
      k['title'] = k['name'];
      k['key'] = k['deviceId'];
      return k;
    });
  });
}

onMounted(() => {
  // created(spilt.value);
  // 初始化站点
  initStation();
});

onUnmounted(() => {
  playList.map((_) => {
    Object.keys(_).map((k) => {
      if (k == '$container') {
        _?.destroy();
      }
    });
  });
});
</script>

<style lang="less" scoped>
.device-container {
  margin: 12px;
  background: #fff;
  .tip {
    width: 100%;
    height: 44px;
    padding: 0 0 0 43.3px;
    background: url('@/assets/images/img-17.png') no-repeat;
    background-size: 100% 100%;
    line-height: 44px;
    :deep(.ant-page-header) {
      height: 44px;
      padding: 0;
      .ant-page-header-heading-left {
        margin: 0;
        .ant-page-header-back {
          .ant-page-header-back-button {
            color: #fff;
          }
        }
        .ant-page-header-heading-title {
          color: #fff;
        }
      }
    }
    span {
      font-size: 16px;
      color: #fff;
    }
  }
  .jeecg-search-layer {
    margin: 0 0 17px;
    padding: 12px 15px;
    background: #fff;
    border-radius: 8px;
    .ant-form {
      max-width: auto;
      .ant-form-item {
        margin-bottom: 24px;
      }
      :deep(.ant-col) {
        width: auto;
      }
    }
  }
  .jeecg-table-view {
    height: calc(100vh - 180px);
    .tree-meun {
      width: 20%;
      height: 98%;
      padding: 12px;
      overflow: hidden;
      overflow-y: scroll;
      .ant-tree {
        .status {
          display: block;
          width: 12px;
          height: 12px;
          margin: 0 0 0 6px;
          border-radius: 50%;
          &.on-line {
            background: #21da13;
          }
          &.off-line {
            background: red;
          }
        }
      }
    }
    .play-container {
      height: 98%;
      margin: 0 12px;
      flex: 1;
      .play-head {
        height: 35px;
        padding: 0 12px 0 0;
        font-size: 20px;
        line-height: 35px;
        .ico {
          display: block;
          width: 24px;
          height: 24px;
          margin: auto 6px;
          cursor: pointer;

          &.icon-1 {
            background: url('@/assets/images/img-42.png');
            background-size: 100%;
            &:hover,
            &.active {
              background: url('@/assets/images/img-45.png');
              background-size: 100%;
            }
          }
          &.icon-2 {
            background: url('@/assets/images/img-43.png');
            background-size: 100%;
            &:hover,
            &.active {
              background: url('@/assets/images/img-46.png');
              background-size: 100%;
            }
          }
          &.icon-3 {
            background: url('@/assets/images/img-44.png');
            background-size: 100%;
            &:hover,
            &.active {
              background: url('@/assets/images/img-47.png');
              background-size: 100%;
            }
          }
        }
      }
      .player-main {
        position: relative;
        height: calc(100% - 35px);
        background: rgb(38, 38, 38);
        .number {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          height: 100%;
          text-align: center;
          line-height: 100%;
          color: #fff;
          font-size: 30px;
          font-weight: bold;
        }
        .player {
          position: relative;
          width: 100%;
          height: 90%;
          background: rgb(38, 38, 38);
          cursor: pointer;
          .video {
            display: block;
            width: 92%;
            height: 100%;
            margin: 0 auto;
          }
          .player-container {
            width: 100%;
            height: 100%;
            background: rgba(13, 14, 27, 0.7);
          }
          .btn-box {
            position: absolute;
            right: 0;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 35px;
            background: rgba(43, 51, 63, 0.7);
            line-height: 35px;
            user-select: none;
            z-index: 100;
            .btn-box-left,
            .btn-box-right {
              .anticon {
                cursor: pointer;
                font-size: 22px;
                color: #fff;
              }
            }
            .btn-box-left {
              flex: 1;
              .anticon {
                margin: 0 12px;
                &:hover {
                  color: #2a82e4;
                }
              }
            }
            .btn-box-right {
              flex: 1;
              color: #fff;
              .anticon {
                margin: 0 12px;
              }
            }
          }
        }
      }
    }
  }
}
</style>